package xiongguanweb

import com.google.gson.Gson
import com.isprint.am.saml.AuthnRequest
import com.isprint.am.saml.sp.SP
import com.isprint.am.saml.sp.SPConfiguration
import grails.converters.JSON
import org.grails.web.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import xiongguanweb.webserviceclient.*

class SamlController {
    def samlService
    private static Logger logger = LoggerFactory.getLogger(SamlController.class)
    /**
     * 获取SamRequest
     * @return
     */
    def getSamlRequest() {
        String AxMxSessionToken = ""
        String authnContext = null
        String idpId = "isprint"
        Set reqIdRepository
        String redirectURL = ""
        SPConfiguration conf = null
//        def samlRequestMap = [:]
        Map<String, String> samlRequestMap = new HashMap<String, String>()
        try {
//            conf = PropKit.use("saml-sp.properties")
            conf = SPConfiguration.newInstance("d:\\Sam\\saml-sp.properties")
//            conf = SPConfiguration.newInstance("C:\\devSrc\\xiongguanweb\\src\\main\\resources\\saml-sp.properties")
            logger.info("conf===============" + conf)
            SP sp = SP.newInstance(conf)
            logger.info("sp==================" + sp)
            List authnContexts = new ArrayList()
            if (authnContext != null) {
                authnContexts.add(authnContext)
            }
            AuthnRequest samlRequest = sp.generateAuthnRequest(idpId, authnContexts)
            reqIdRepository = new HashSet()
            reqIdRepository.add(samlRequest.getRequestId())
            String spRelayState = URLEncoder.encode("/test.jsp", "UTF-8")
            samlRequestMap.put("url", samlRequest.getSSOUrl())
            String samlRequestStr = samlRequest.getUrlEncodedAndDeflatedSAMLRequest()
            logger.info("samlrequest-------" + samlRequestStr)
            samlRequestMap.put("SAMLRequest", samlRequestStr)
            samlRequestMap.put("RelayState", spRelayState)
            samlRequestMap.put("systemname", "xgbmk")
            Gson gson = new Gson()
            redirectURL = gson.toJson(samlRequestMap)
        } catch (Exception_Exception e) {
            logger.error("getSamlRequest Exception ==${e}")
        }
        render samlRequestMap as JSON
    }

    /**
     * 根据id获取SAMLResponse
     */
    def getSamlResponse() {
        logger.info("step1")
        def samlid = "${params.samlid}"
        def samltoken = "${params.samltoken}"
        logger.info("samlid====" + samlid)
        logger.info("samltoken====" + samltoken)
        def data = [:]
        CcServiceInObj ccServiceInObj = new CcServiceInObj()
        JSONObject jsonObject = new JSONObject()
        jsonObject.put("method", "get")
        jsonObject.put("id", samlid)
        ccServiceInObj.setSystemName("xgbmk")
        ccServiceInObj.setClient("PC")
        ccServiceInObj.setJsonObj(jsonObject.toString())
        CcServiceOutObj out = null
        CCWebSrv service = new CCWebSrv()
        ICCWebSrv serviceImp = service.getCCWebSrvPort()
        logger.info("step3")
        try {
            logger.info("step4")
            out = serviceImp.getOrSetSamlResponseData(ccServiceInObj)
            logger.info("erroecode=====" + out.getErrorCode())
            String jsonobj = out.getJsonObj()
            logger.info("jsonobj=====" + jsonobj)
            data.code = out.getErrorCode()
            JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonobj)
            logger.info("jsonObject1=====" + jsonObject1)
            logger.info("samlresponse" + jsonObject1.getString("samlResponse"))
            def samlData = samlService.getSamlData(jsonObject1.getString("samlResponse"))
            if(samlData.size() >0){
            data += samlData
            logger.info("useruuid====" + data.useruuid.split(":")[1])
            session.setAttribute("uuid", data.useruuid.split(":")[1])
            session.setAttribute("samltoken", samltoken)
            logger.info("mobile====" + data.mobile)
            session.setAttribute("mobile", data.mobile)
            logger.info("data=====" + data)
            }else {
                data.code = 11
            }
        } catch (Exception_Exception e) {
            e.printStackTrace()
        }
        logger.info("samlogin == errorCode:" + out.getErrorCode())
        render data as JSON
    }

    /**
     * 本地测试方法 12a12b
     */
    def gettestsamlResponse() {
        def data = [:]
        session.setAttribute("samltoken", "10001L-WwCeGSmwuBOfSPqZZICKDhcaHJGfG8SZ-gotIKDcdCBD058oQ2-SGSA7dJPnTZ1D3aQ47NiWEyVjCyJiKsY552yeU2w1JxQRe2rIqGshw3WY2IBJ_SfK7KYgoauLuzDXtcrRz8wOsNloUoCXYiT0Y7-YWlQXySJTIsF1OPljJH4-01_mV1m8HnsLpOaljZM5zGbrJ1r75VjwJD2GnC31jhxRL_z9grJ6O561O2k0D9uRZLbKjIn4b19fKkA_77jnXcz8ft5GX5vZfkgHQe9XYPIwCu6LxixL4")
        session.setAttribute("mobile", "15268190596")
        session.setAttribute("uuid", "c126d60a3b0f43cfade1aa848d3fa971")
        data.code = "2300"
        render data as JSON
    }
}

